package com.ruoyi.publish.service.impl;

import java.util.Calendar;
import java.util.List;

import com.ruoyi.common.annotation.ExcelImportAdvice;
import com.ruoyi.common.enums.TaskWorkFlowStaus;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtilTool;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.publish.domain.*;
import com.ruoyi.publish.mapper.IdIdentsampleMapper;
import com.ruoyi.publish.service.IApprovalRecordService;
import com.ruoyi.system.domain.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.publish.mapper.IdReportMapper;
import com.ruoyi.publish.service.IIdReportService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 鉴定报告Service业务层处理
 *
 * @author confusefox
 * @date 2020-11-17
 */
@Service
public class IdReportServiceImpl implements IIdReportService {

    private static final Logger log = LoggerFactory.getLogger(IdReportServiceImpl.class);
    @Autowired
    private IdReportMapper idReportMapper;
    @Autowired
    private IdIdentsampleMapper idIdentsampleMapper;

    @Autowired
    private IApprovalRecordService approvalRecordService;

    /**
     * 查询鉴定报告
     *
     * @param id 鉴定报告ID
     * @return 鉴定报告
     */
    @Override
    public IdReport selectIdReportById(Long id) {
        return idReportMapper.selectIdReportById(id);
    }

    /**
     * 查询鉴定报告列表
     *
     * @param idReport 鉴定报告
     * @return 鉴定报告
     */
    @Override
    public List<IdReport> selectIdReportList(IdReport idReport) {
        return idReportMapper.selectIdReportList(idReport);
    }

    /**
     * 新增鉴定报告
     *
     * @param idReport 鉴定报告
     * @return 结果
     */
    @Override
    public int insertIdReport(IdReport idReport) {
        idReport.setCreateTime(DateUtils.getNowDate());
        if(idReport.getAcceptTime()==null){
            idReport.setAcceptTime(DateUtils.getNowDate());
        }

        idReport.setApprovalLevel(1);
        // 鉴定报告初始状态为草稿
        idReport.setStatus(TaskWorkFlowStaus.No_Start.getValue().toString());

//      找到对应的 样本记录
        String sampleids = idReport.getSampleIds();
        String[] idArgs = sampleids.split(",");
        // 启用状态 默认为 1 启用
        if (StringUtils.isEmpty(idReport.getIsUse())) {
            idReport.setIsUse("1");
        }
        idReport.setSampleNumber((long) idArgs.length);

        //文书编号
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);

        String by1 = null;
        SelfIncreasingReport selfIncreasingReport = idReportMapper.findByYear(year);
        /*自增数拼接*/
        if (selfIncreasingReport == null) {
            selfIncreasingReport = new SelfIncreasingReport();
            by1 = String.valueOf(year + "-0001");
            selfIncreasingReport.setNum(1);
            selfIncreasingReport.setYear(year);
            idReportMapper.insertSelfIncreasingReport(selfIncreasingReport);
        } else {
            int num = idReportMapper.findByYear(year).getNum() + 1;
            by1 = String.valueOf(year + "-" + StringUtilTool.numberSupplement(String.valueOf(num), 4));
            selfIncreasingReport.setNum(num);
            selfIncreasingReport.setYear(year);
            idReportMapper.updateSelfIncreasingReport(selfIncreasingReport);
        }
        idReport.setBy1(by1);


        int retnum = idReportMapper.insertIdReport(idReport);
        if (idArgs.length > 0) {
            for (String id : idArgs) {
                long idlong = Long.parseLong(id);
                IdIdentsample sample = idIdentsampleMapper.selectIdIdentsampleById(idlong);
                sample.setBy1(idReport.getId().toString());

                //设置样本鉴定状态为鉴定中

                sample.setStatus("1");
                idIdentsampleMapper.updateIdIdentsample(sample);
            }
        }
        return retnum;
    }

    /**
     * 修改鉴定报告
     *
     * @param idReport 鉴定报告
     * @return 结果
     */
    @Override
    public int updateIdReport(IdReport idReport) {
        idReport.setUpdateTime(DateUtils.getNowDate());

        // 如果修改了审批人，则清空历史审批和审批状态
        IdReport recordReport = idReportMapper.selectIdReportById(idReport.getId());

        if (recordReport.getApprovalLevel() == 0) {
            idReport.setApprovalLevel(1);
        } else {
            idReport.setApprovalLevel(recordReport.getApprovalLevel());
        }

        if (StringUtils.isNotEmpty(idReport.getSampleIds())) {
            // 如果修改了关联样本 样本的发生变化
            //导入数据默认 没有sampleId 编辑时候不判断修改
            if (StringUtils.isNotEmpty(recordReport.getSampleIds())) {
                if (!recordReport.getSampleIds().equals(idReport.getSampleIds())) {
                    IdIdentsample queryList = new IdIdentsample();
                    queryList.setBy1(String.valueOf(recordReport.getId()));
                    //找到相应
                    List<IdIdentsample> sampleLists = idIdentsampleMapper.selectIdIdentsampleList(queryList);

                    for (IdIdentsample sampleEntity : sampleLists) {
//                        sampleEntity.setBy1(null);
                        //设置样本状态为未鉴定
                        sampleEntity.setStatus("0");
                        idIdentsampleMapper.updateIdIdentsample(sampleEntity);
                        idIdentsampleMapper.idSampleToNull(sampleEntity.getId()); //修改成指定sql
                    }
                    //      找到对应的 样本记录
                    String sampleids = idReport.getSampleIds();
                    if (StringUtils.isNotEmpty(sampleids)) {
                        String[] idArgs = sampleids.split(",");
                        idReport.setSampleNumber((long) idArgs.length);
                        if (idArgs.length > 0) {
                            for (String id : idArgs) {
                                long idlong = Long.parseLong(id);
                                IdIdentsample sample = idIdentsampleMapper.selectIdIdentsampleById(idlong);
                                sample.setBy1(idReport.getId().toString());
                                //设置样本状态为鉴定中
                                sample.setStatus("1");
                                idIdentsampleMapper.updateIdIdentsample(sample);
                            }
                        }
                    }
                }

            } else {
                //      找到对应的 样本记录
                String sampleids = idReport.getSampleIds();
                if (StringUtils.isNotEmpty(sampleids)) {
                    String[] idArgs = sampleids.split(",");
                    idReport.setSampleNumber((long) idArgs.length);
                    if (idArgs.length > 0) {
                        for (String id : idArgs) {
                            long idlong = Long.parseLong(id);
                            IdIdentsample sample = idIdentsampleMapper.selectIdIdentsampleById(idlong);
                            sample.setBy1(idReport.getId().toString());
                            //设置样本状态为鉴定中
                            sample.setStatus("1");
                            idIdentsampleMapper.updateIdIdentsample(sample);
                        }
                    }
                }
            }

        }

        return idReportMapper.updateIdReport(idReport);
    }

    /**
     * 删除鉴定报告对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteIdReportByIds(String ids) {
        return idReportMapper.deleteIdReportByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除鉴定报告信息
     *
     * @param id 鉴定报告ID
     * @return 结果
     */
    @Override
    public int deleteIdReportById(Long id) {
        return idReportMapper.deleteIdReportById(id);
    }

    /**
     * 改变记录启用状态
     *
     * @param idReport 鉴定样本ID
     * @return 结果
     */
    @Override
    public int changeStatus(IdReport idReport) {
        return idReportMapper.updateIdReport(idReport);
    }

    //导入鉴定报告
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public String importIdReport(List<IdReport> idReportList, Boolean isUpdateSupport, String operId, String operName, String year) {
        if (StringUtils.isNull(idReportList) || idReportList.size() == 0) {
            throw new BusinessException("导入案件数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int reSetNum = 0;
        int orderNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String num = idReportMapper.getReportCode();
        for (IdReport entity : idReportList) {
            orderNum++;
            if (StringUtils.isEmpty(entity.getAppraCon())) {
                continue;
            }
            try {
                entity.setCreateTime(DateUtils.getNowDate());
                entity.setAcceptTime(DateUtils.getNowDate());

                entity.setCreateBy(operId);
                entity.setTakeover(operName);
                entity.setApprovalLevel(1);//审读层级
                entity.setStatus(TaskWorkFlowStaus.No_Start.getValue().toString());//草稿
                entity.setIsUse("0"); //未启用状态

                entity.setBy1(num.split("-")[0] + "-" + String.valueOf(Integer.parseInt(num.split("-")[1]) + successNum));

                //保存记录
                int u = 0;
                if (StringUtils.isNotEmpty(entity.getAppraCon()) && StringUtils.isNotEmpty(entity.getIdentiContent())) {
                    u = idReportMapper.insertIdReport(entity); //修改为server 赋值序号

                }


                // 验证是否保成功
                if (u == 1) {

                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginName() + " 导入成功");
                } else {
                    failureNum++;
//                    failureMsg.append("<b
//                    r/>" + failureNum + "、账号 " + user.getLoginName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + " 导入失败：";
                // failureMsg.append(e.getMessage());
                log.error(msg, e);
            }
            orderNum++;
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        } else {
            // String resString = "未在系统中找到相应的审核组长请之后设置鉴定组长！g共" + reSetNum + "条,";
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条");
        }
        return successMsg.toString();
    }

    @Override
    public int IdReportRefreshByRecordId(Long id) {
        return idReportMapper.IdReportRefreshByRecordId(id);
    }

    /**
     * 根据Id获取数据
     *
     * @param ids
     * @return
     */
    @Override
    public List<IdReport> selectRecordByIds(String[] ids) {
        return idReportMapper.selectRecordByIds(ids);
    }

    @Override
    public List<IdReport> selectRecordByRegisterId(Long id) {
        return idReportMapper.selectRecordByRegisterId(id);
    }
}
